#!/usr/bin/env python
# encoding: utf-8
'''
python3.6+
启动
  python flaskFileServer.py
安装依赖
 pip install flask==0.12.2 -i https://pypi.tuna.tsinghua.edu.cn/simple

'''

from flask import Flask, render_template, request, redirect, url_for, send_from_directory
import os
import time
from datetime import timedelta

upload_path = os.path.join(os.path.dirname(__file__), 'upload')
if not os.path.exists(upload_path):
    os.makedirs(upload_path)

# 设置允许的文件格式
ALLOWED_EXTENSIONS = ['png', 'jpg', 'JPG', 'PNG', 'bmp']


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


app = Flask(__name__)


@app.route('/')
def index():
    print(upload_path)

    items = []
    for filename in os.listdir(upload_path):
        file = os.stat(os.path.join(upload_path,filename))


        st_mtime_date= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(file.st_mtime)))


        items.append({"filename":filename,
                      "st_size":file.st_size,
                      # "st_atime":file.st_atime,
                      "st_mtime_date":st_mtime_date,
                      # "st_ctime":file.st_ctime
                      })

    return render_template('templates/index.html', items=items)
@app.route("/download")
def download():

    filename= request.args.get("filename")

    print(upload_path)
    print(filename)

    # return send_from_directory(r"D:\desk\id",filename="123.jpg",as_attachment=True)
    return send_from_directory(upload_path,filename=filename,as_attachment=True)
# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)
# @app.route('/upload', methods=['POST', 'GET'])
@app.route('/upload', methods=['POST', 'GET'])  # 添加路由
def upload():
    if request.method == 'POST':
        try:
            f = request.files['file']
            # if not (f and allowed_file(f.filename)):
            #
            #     return jsonify({"error": 1001, "msg": "请检查上传的图片类型，仅限于png、PNG、jpg、JPG、bmp"})


            name = request.form.get("name")

            filename = os.path.join(upload_path,"%s_%s"%(name,f.filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径

            f.save(filename)
            return redirect(url_for("index"))
        except Exception as e:

            return render_template('template/upload.html', msg="上传失败：%s" % str(e))

    else:

        return render_template('template/upload.html')


if __name__ == '__main__':
    # app.debug = True
    app.run(host='0.0.0.0', port=9000, debug=False)